package ncut.shumei.service.impl;

import ncut.shumei.dao.UserDao;
import ncut.shumei.dto.LoginRequest;
import ncut.shumei.dto.LoginResponse;
import ncut.shumei.dto.RegisterRequest;
import ncut.shumei.dto.UserDTO;
import ncut.shumei.entity.User;
import ncut.shumei.exception.BusinessException;
import ncut.shumei.service.AuthService;
import ncut.shumei.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserDao userDao;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        return user;
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        User user = userDao.findByUsername(request.getUsername());
        log.debug("Login attempt for user: {}", request.getUsername());
        
        if (user == null) {
            log.debug("User not found: {}", request.getUsername());
            throw new BusinessException("用户名或密码错误");
        }
        
        log.debug("Found user: {}, stored password: {}", user.getUsername(), user.getPassword());
        log.debug("Input password: {}, encoded: {}", request.getPassword(), 
            passwordEncoder.encode(request.getPassword()));
        
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            log.debug("Password mismatch for user: {}", request.getUsername());
            throw new BusinessException("用户名或密码错误");
        }
        
        String token = jwtUtil.generateToken(user.getUsername());
        log.debug("Login successful for user: {}", request.getUsername());
        
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUser(userDTO);
        return response;
    }

    @Override
    @Transactional
    public UserDTO register(RegisterRequest request) {
        // 验证用户名是否已存在
        if (userDao.findByUsername(request.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole("MAINTAINER");  // 默认注册为维护人员
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setStatus(1);  // 默认启用
        
        userDao.insert(user);
        
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        return userDTO;
    }

    @Override
    public User validateToken(String token) {
        String username = jwtUtil.getUsernameFromToken(token);
        if (username == null) {
            return null;
        }
        return userDao.findByUsername(username);
    }

    @Override
    public String generateToken(String username) {
        return jwtUtil.generateToken(username);
    }
} 